package Reference;

import java.lang.ref.SoftReference;

/**
 * @Author: dch
 * @Date: 2020/5/18 13:55
 * @Description:
 */
public class SoftReferenceDemo {
    /**
     * 演示内存充足情况
     */
    public static void SoftRefMemoryEnough(){
        //默认强引用
        Object obj1 = new Object();
        //软引用,内存充足不回收
        SoftReference<Object> softReference = new SoftReference<Object>(obj1);
        //赋值null
        obj1 = null;
        //手动回收
        System.gc();
        System.out.println(obj1);//输出 null
        System.out.println(softReference.get());//输出 java.lang.Object@65b3120a
    }
    /**
     *JVM配置，故意产生大对象并配置小的内存，让它内存不够导致OOM，看软引用的回收情况
     * 即在Run--->Edit Configruations--->VM options添加下面参数
     * -Xms5m -Xmx5m -XX:+PrintGCDetails
     */
    public static void SoftRefMemoryNotEnough(){
        //默认强引用
        Object obj1 = new Object();
        //软引用,内存充足不回收
        SoftReference<Object> softReference = new SoftReference<Object>(obj1);
        //赋值null
        obj1 = null;
        //产生大对象
        try{
            byte[] bytes = new byte[30*1024*1024];
        }catch (Throwable e){
            e.printStackTrace();
        }finally {
            System.out.println(obj1);//输出 null
            System.out.println(softReference.get());//输出 java.lang.Object@65b3120a
        }
    }
    public static void main(String[] args) {
        //SoftRefMemoryEnough();
        SoftRefMemoryNotEnough();
    }
}
